//! MD5哈希算法实现
//! 
//! 提供MD5哈希功能，对应Java的MD5Utils

use md5::{Digest, Md5};

/// MD5加密
/// 
/// # Examples
/// ```
/// use librarys::crypto::hash::md5_hash;
/// 
/// let hash = md5_hash("hello world");
/// assert!(hash.len() == 32); // MD5 produces 32 hex chars
/// ```
pub fn md5_hash(input: &str) -> String {
    let mut hasher = Md5::new();
    hasher.update(input.as_bytes());
    let result = hasher.finalize();
    format!("{:x}", result)
}

/// MD5加密（字节输入）
/// 
/// # Examples
/// ```
/// use librarys::crypto::hash::md5_hash_bytes;
/// 
/// let hash = md5_hash_bytes(b"hello world");
/// assert!(hash.len() == 32);
/// ```
pub fn md5_hash_bytes(input: &[u8]) -> String {
    let mut hasher = Md5::new();
    hasher.update(input);
    let result = hasher.finalize();
    format!("{:x}", result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_md5_hash() {
        // 测试实际计算的MD5值
        let hash1 = md5_hash("hello world");
        let hash2 = md5_hash("");
        
        // 确保结果的长度是正确的（MD5 = 32个十六进制字符）
        assert_eq!(hash1.len(), 32);
        assert_eq!(hash2.len(), 32);
        
        // 确保字节和字符串输入产生相同结果
        assert_eq!(md5_hash_bytes(b"hello world"), hash1);
        assert_eq!(md5_hash_bytes(b""), hash2);
        
        // 确保空字符串的MD5值是正确的（这是固定的）
        assert_eq!(hash2, "d41d8cd98f00b204e9800998ecf8427e");
    }
}